package com.yuanxuzhen.androidmedia.audio;

import android.Manifest;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.yuanxuzhen.androidmedia.DirUtil;
import com.yuanxuzhen.androidmedia.R;
import com.yuanxuzhen.androidmedia.databinding.ActivityAudioBinding;
import com.yuanxuzhen.androidmedia.databinding.ActivityMainBinding;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class AudioActivity extends AppCompatActivity {
    ActivityAudioBinding mainBinding;
    AudioRecord audioRecord;
    int recordBufSize = 0; // 声明recoordBufffer的大小字段
    public static final int SAMPLE_RATE = 44100; //采样率
    public static final int CHANNEL_NUM = 2; //声道数
    public static final int AUDIO_FORMATE = AudioFormat.ENCODING_PCM_16BIT; //采样大小
    public static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_STEREO; //声道数
    private byte[] buffer;
    private ExecutorService mExecutors;
    private boolean isRecording;
    private String pcmFileName;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        File parentFile = new File(DirUtil.getCacheDir());
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }

        pcmFileName = DirUtil.getCacheDir() + File.separator + "audio.pcm";
        mExecutors = Executors.newCachedThreadPool();
        mainBinding = ActivityAudioBinding.inflate(getLayoutInflater());
        setContentView(mainBinding.getRoot());
        mainBinding.start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AudioActivityPermissionsDispatcher.openAudioWithPermissionCheck(AudioActivity.this);
            }
        });
        mainBinding.stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isRecording = false;
                mainBinding.tvStatus.setText("开始录制");
                audioRecord.stop();
            }
        });
        mainBinding.startPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mainBinding.tvStatus.setText("正在播放");
                AudioTrackManager.getInstance().startPlay(pcmFileName);
                audioRecord.stop();
            }
        });
        mainBinding.stopPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AudioTrackManager.getInstance().stopPlay();
                mainBinding.tvStatus.setText("停止播放");

            }
        });

        mainBinding.wavplay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WavPlayer.getInstance().startPlay(DirUtil.getCacheDir() + File.separator + "out.wav");
            }
        });
        mainBinding.wavstop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WavPlayer.getInstance().stopPlay();
            }
        });
    }

    @NeedsPermission(Manifest.permission.RECORD_AUDIO)
    public void openAudio() {
        Log.e("yuanAudio", "openAudio");
        recordBufSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMATE);
        Log.e("yuanAudio", "recordBufSize =" + recordBufSize);
        Log.e("yuanAudio", "Calculation recordBufSize =" + (44100 * 2 * 2));
        audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
                SAMPLE_RATE,
                CHANNEL_CONFIG,
                AUDIO_FORMATE,
                recordBufSize
        );
        buffer = new byte[recordBufSize];
        audioRecord.startRecording();
        isRecording = true;
        mainBinding.tvStatus.setText("正在录制");
        mExecutors.execute(new Runnable() {
            @Override
            public void run() {
                FileOutputStream os = null;
                try {
                    if (!new File(pcmFileName).exists()) {
                        new File(pcmFileName).createNewFile();
                    }
                    os = new FileOutputStream(pcmFileName);
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }

                if (null != os) {
                    while (isRecording) {
                        int read = audioRecord.read(buffer, 0, recordBufSize);

                        // 如果读取音频数据没有出现错误，就将数据写入到文件
                        if (AudioRecord.ERROR_INVALID_OPERATION != read) {
                            try {
                                os.write(buffer);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }
        });

    }


    @OnPermissionDenied(Manifest.permission.RECORD_AUDIO)
    public void onDenied() {
        Toast.makeText(this, "录音权限拒绝", Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain(Manifest.permission.RECORD_AUDIO)
    public void onNeverAskAgain() {
        Toast.makeText(this, "录音权限再不询问", Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AudioActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

}